import Request from "@/lib/request/index.js";
import storage from "@/utils/storage.js";
import api from "@/config/api.js";
import store from "../store";
import {
	login
} from '@/utils/mbti-login.js'

// 白名单  无需token
let whiteList = [
	"/user/wechatLogin",
	"/user/wechatRegister",
	"/user/getWechatMobile",
	"/auth/wechat/login",
	"/auth/wechat/register"
]


let http = new Request();
http.setConfig((config) => {
	/* 设置全局配置 */
	config.baseURL = api.buyer;
	config.header = {
		...config.header,
	};
	config.validateStatus = (statusCode) => {
		// 不论什么状态,统一在正确中处理
		return true;
	};
	return config;
});

http.interceptors.request.use(
	(config) => {
		let accessToken = storage.getAccessToken();
		let url = config.url
		if (!accessToken && !whiteList.includes(url)) {
			let curPage = getCurrentPages()[getCurrentPages().length - 1];
			let route = curPage.route
			if (route != "pages/runChat/collectInformation") {
				uni.navigateTo({
					url: "/pages/runChat/collectInformation"
				})

			}
		} else {
			config.header.Authorization = accessToken;
		}
		config.header.Authorization = accessToken;
		config.header = {
			...config.header,
		};
		return config;
	},
	(config) => {
		return Promise.reject(config);
	}
);
// 是否正在刷新的标记
let isRefreshing = false;
//重试队列
let requests = [];

// 必须使用异步函数，注意
http.interceptors.response.use(
	async (response) => {
			let code = response.data.code
			if (code == '401') {
				if (!isRefreshing) {
					isRefreshing = true
					// 修改1：添加return保证返回Promise链
					return login().then(res => {
						let accessToken = storage.getAccessToken()
						requests.forEach((cb) => {
							cb(accessToken) // 修改2：移除return，直接执行回调
						});
						requests = [];
						// 修改3：返回新请求并带出Promise链
						return http.request(response.config);
					}).catch((err) => {
						return Promise.reject(err);
					}).finally(() => {
						isRefreshing = false;
					});
				} else {
					return new Promise((resolve) => {
						requests.push((token) => {
							response.header.Authorization = `${token}`;
							resolve(http.request(response.config));
						});
					});
				}

			} else {
				return response.data;
			}

			return response;
		},
		(error) => {
			return error;
		}
);

export {
	http
};

export const Method = {
	GET: "GET",
	POST: "POST",
	PUT: "PUT",
	DELETE: "DELETE",
};